package com.ocom.app.config;

import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

/**
 * 资源服务配置
 */
@Configuration
@EnableResourceServer
@AllArgsConstructor
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

  private final TokenStore tokenStore;

  /**
   * token服务配置
   */
  @Override
  public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
    //这里把自定义异常加进去
    resources.tokenStore(tokenStore).authenticationEntryPoint(new AuthExceptionEntryPoint())
        .accessDeniedHandler(new CustomAccessDeniedHandler());
  }

  /**
   * 路由安全认证配置
   */
  @Override
  public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        // 配置hello打头的路由需要安全认证，order无配置无需认证
        .antMatchers("/feign/**").permitAll()
        .antMatchers("/usr/wx/bind").permitAll()
         .antMatchers("/sendsms").permitAll()
        .antMatchers("/campus/sendsms").permitAll()
        .antMatchers("/**").authenticated()
        .and().csrf().disable();
  }

  /**
   * jwt token 校验解析器
   */
  @Bean
  public TokenStore tokenStore(JwtAccessTokenConverter accessTokenConverter) {
    return new JwtTokenStore(accessTokenConverter);
  }

}
